package com.yz.controller;

import com.yz.core.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @className: fileController
 * @author: shuishui
 * @date: 2023/01/05 18:59
 */
@RestController
@RequestMapping("/fileController")
@Slf4j
public class fileController {
    @Value("${blog.uploadPath}")
    private String uploadPath;

    @PostMapping("/upload")
    public R upload(@RequestParam("pngFile") MultipartFile file){
        FileOutputStream ops = null;
        InputStream inputStream = null;
        String filePath = uploadPath + file.getOriginalFilename();//获得上传文件的名字
        try {
            inputStream = file.getInputStream();
            ops = new FileOutputStream(filePath);
            IOUtils.copy(inputStream,ops);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok().put("data", filePath);
    }
    @GetMapping("/showPng")
    @ResponseBody
    public void showPng(String filePath, HttpServletResponse resp) {

        FileInputStream ips = null;
        try {
            try {
                ips = new FileInputStream(filePath); // 从本地找，
            } catch (FileNotFoundException e) {
               return;
            }
            IOUtils.copy(ips, resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ips);
        }
    }
}
